const createHash = require('create-hash')
module.exports = {
  // 对请求结果统一封装处理
  handleResponse(err, response, body) {
    if (!err && response.statusCode == '200') {
      let data = JSON.parse(body);

      if (data && !data.errcode) {
        return this.handleSuc(data);
      } else {
        return this.handleFail(data.errmsg, data.errcode);
      }
    } else {
      return this.handleFail(err, 10009);
    }
  },
  handleSuc(data = '') {
    return {
      code: 0,
      data,
      message: ''
    }
  },
  handleFail(message = '', code = 10001) {
    return {
      code,
      data: '',
      message
    }
  },
  // 生成随机数
  createNonceStr() {
    return Math.random().toString(36).substr(2, 15);
  },
  // 生成时间戳
  createTimeStamp() {
    return parseInt(new Date().getTime() / 1000) + ''
  },
  raw(params) {
    let str = '';
    Object.keys(params).sort().forEach(item => {
      str += `&${item}=${params[item]}`
    })
    return str.substr(1)
  },
  getSign(params, key){
    let string = this.raw(params) + '&key=' + key;
    let sign = createHash('md5').update(string).digest('hex');
    return sign.toUpperCase();
  },
  randerOrderNum() {
    const now = new Date()
    let month = now.getMonth() + 1
    let day = now.getDate()
    let hour = now.getHours()
    let minutes = now.getMinutes()
    let seconds = now.getSeconds()
    month = setTimeDateFmt(month)
    day = setTimeDateFmt(day)
    hour = setTimeDateFmt(hour)
    minutes = setTimeDateFmt(minutes)
    seconds = setTimeDateFmt(seconds)
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds

    for (var i = 0; i < 18; i++) //6位随机数，用以加在时间戳后面。
    {
      orderCode += Math.floor(Math.random() * 10);
    }
    return orderCode
  }
}
function setTimeDateFmt(s) {  // 个位数补齐十位数
  return s < 10 ? '0' + s : s;
}